package com.ruoyi.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.entity.SisApprove;
import com.ruoyi.system.entity.SisConfig;
import com.ruoyi.system.entity.SisInventoryCount;
import com.ruoyi.system.entity.SisPhase;
import com.ruoyi.system.mapper.SisApproveMapper;
import com.ruoyi.system.mapper.SisConfigMapper;
import com.ruoyi.system.mapper.SisPhaseMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.SisApproveService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * (SisApprove)表服务实现类
 *
 * @author makejava
 * @since 2023-08-01 10:17:49
 */
@Service("sisApproveService")
public class SisApproveServiceImpl implements SisApproveService {
    @Resource
    private SisApproveMapper sisApproveMapper;

    @Resource
    private SisConfigMapper sisConfigMapper;

    @Resource
    private SisPhaseMapper sisPhaseMapper;

    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private EnterpriseWXServiceImpl enterpriseWXService;


    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public SisApprove queryById(Integer id) {
        return this.sisApproveMapper.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param sisApprove 筛选条件
     * @return 查询结果
     */
    @Override
    public List<SisApprove> queryByPage(SisApprove sisApprove) {
        List<SisApprove> sisApproves = this.sisApproveMapper.queryAllByLimit(sisApprove);
        for (SisApprove approve : sisApproves) {
            SisPhase sisPhase = new SisPhase();
            sisPhase.setApproveId(approve.getId());
            approve.setSisPhases(sisPhaseMapper.queryAllByLimit(sisPhase));
        }
        return sisApproves;
    }

    /**
     * 新增数据
     *
     * @param sisApprove 实例对象
     * @return 实例对象
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public SisApprove insert(SisApprove sisApprove) {
        sisApprove.setState("审批中");
        List<SisConfig> sisConfigs = sisConfigMapper.queryAllByLimit(new SisConfig());
        if (CollUtil.isEmpty(sisConfigs)) {
            throw new ServiceException("请配置节点审批人", 500);
        }
        sisApprove.setPhase(1);
        sisApprove.setCreateUserName(SecurityUtils.getLoginUser().getUser().getNickName());
        sisApprove.setCreateUserId(SecurityUtils.getUserId().intValue());
        this.sisApproveMapper.insert(sisApprove);
        Integer id = sisApprove.getId();
        List<SisPhase> sisPhases = new ArrayList<>();
        for (SisConfig sisConfig : sisConfigs) {
            SisPhase sisPhase = new SisPhase();
            BeanUtils.copyBeanProp(sisPhase, sisConfig);
            sisPhase.setApproveId(id);
            if (sisConfig.getPhase() == 1) {
                sisApprove.setPhaseUserName(sisConfig.getUserName());
                sisPhase.setState("审批中");

                String userId = sisPhase.getUserId();
                if (userId.contains(",")) {
                    String[] split = userId.split(",");
                    for (String var : split) {
                        sengwx(Integer.valueOf(var), sisApprove, sisPhase.getTitle());
                    }
                } else {
                    sengwx(Integer.valueOf(userId), sisApprove, sisPhase.getTitle());
                }

            } else {
                sisPhase.setState("待审批");
            }
            sisPhases.add(sisPhase);
        }
        sisApproveMapper.update(sisApprove);
        sisPhaseMapper.insertBatch(sisPhases);
        return sisApprove;
    }

    @Override
    public void approve(SisApprove sisApprove) {
        Integer id = sisApprove.getId();
        int userId = SecurityUtils.getUserId().intValue();
        Integer phase = sisApprove.getPhase();
        SisPhase query = new SisPhase();
        query.setApproveId(id);
        List<SisPhase> sisPhases = sisPhaseMapper.queryAllByLimit(query);

        List<Integer> userIds = new ArrayList<>();
        SisConfig sisConfig = new SisConfig();
        sisConfig.setPhase(phase);
        List<SisConfig> sisConfigs = sisConfigMapper.queryAllByLimit(sisConfig);
        SisConfig config = sisConfigs.stream().findFirst().orElse(new SisConfig());
        boolean contains = config.getUserId().contains(",");
        if (contains) {
            String[] split = config.getUserId().split(",");
            for (String var : split) {
                userIds.add(Integer.valueOf(var));
            }
        } else {
            userIds.add(Integer.valueOf(config.getUserId()));
        }


        for (int i = 0; i < sisPhases.size(); i++) {
            SisPhase sisPhase = sisPhases.get(i);
            Integer phase1 = sisPhase.getPhase();
            if (phase.equals(phase1)) {
               /* if (sisPhase.getUserId() != userId) {
                    throw new ServiceException("请登录当前节点审批人账号审批", 500);
                }*/

                if (!userIds.contains(userId)) {
                    throw new ServiceException("请登录当前节点审批人账号审批", 500);
                }

                sisPhase.setState(sisApprove.getStatus());
                sisPhase.setSignUrl(sisApprove.getSignUrl());
                sisPhase.setExplainInfo(sisApprove.getExplainInfo());
                sisPhaseMapper.update(sisPhase);
                if (sisPhase.getState().equals("已驳回")) {
                    sisApprove.setState("已驳回");
                    sisApproveMapper.update(sisApprove);
                } else {
                    if (sisPhases.size() < phase + 1) {
                        sisApprove.setState("已通过");
                        sisApproveMapper.update(sisApprove);
                    } else {
                        sisApprove.setPhaseUserName(sisPhases.get(phase1).getUserName());
                        sisApprove.setPhase(phase + 1);
                        sisApproveMapper.update(sisApprove);
                        SisPhase update = new SisPhase();
                        update.setId(sisPhase.getId() + 1);
                        update.setState("审批中");
                        sisPhaseMapper.update(update);
                        SisPhase sisPhaseNext = sisPhases.get(i + 1);
                        if (null != sisPhaseNext) {

                            String userIdOne = sisPhase.getUserId();
                            if (userIdOne.contains(",")) {
                                String[] split = userIdOne.split(",");
                                for (String var : split) {
                                    sengwx(Integer.valueOf(var), sisApproveMapper.queryById(id), sisPhases.get(i + 1).getTitle());
                                }
                            } else {
                                sengwx(Integer.valueOf(userIdOne), sisApproveMapper.queryById(id), sisPhases.get(i + 1).getTitle());
                            }

                            //sengwx(sisPhaseNext.getUserId(), sisApproveMapper.queryById(id), sisPhases.get(i + 1).getTitle());
                        } else {

                            String userIdTwo = sisPhase.getUserId();
                            if (userIdTwo.contains(",")) {
                                String[] split = userIdTwo.split(",");
                                for (String var : split) {
                                    sengwx(Integer.valueOf(var), sisApproveMapper.queryById(id), sisPhases.get(i + 1).getTitle());
                                }
                            } else {
                                sengwx(Integer.valueOf(userIdTwo), sisApproveMapper.queryById(id), sisPhases.get(i + 1).getTitle());
                            }

                            //sengwx(sisPhase.getUserId(), sisApproveMapper.queryById(id), sisPhases.get(i + 1).getTitle());
                        }
                    }
                }
                break;
            } else {
                if (sisPhase.getState().equals("审批中") || sisPhase.getState().equals("已驳回")) {
                    throw new ServiceException("请按照流程节点顺序审批", 500);
                }
            }
        }
    }

    @Override
    public SisInventoryCount getInventoryCount() {
        SisInventoryCount sisInventoryCount = new SisInventoryCount();

        //是否为审批
        String userId = SecurityUtils.getUserId().toString();

        SisConfig sisConfig = new SisConfig();
        List<SisConfig> sisConfigs = sisConfigMapper.queryAllByLimit(sisConfig);
        if (CollectionUtils.isEmpty(sisConfigs)) {
            sisInventoryCount.setIsApproval(0);
        } else {
            for (SisConfig config : sisConfigs) {
                boolean contains = config.getUserId().contains(",");
                if (contains) {
                    String[] split = config.getUserId().split(",");
                    for (String s : split) {
                        if (userId.equals(s)) {
                            sisInventoryCount.setIsApproval(1);
                        }
                    }
                } else {
                    if (userId.equals(config.getUserId())) {
                        sisInventoryCount.setIsApproval(1);
                    }
                }
            }
        }

        //我的申请数量
        SisApprove sisApprove = new SisApprove();
        sisApprove.setCreateUserId(Integer.valueOf(userId));
        List<SisApprove> sisApproves = sisApproveMapper.queryAllByLimit(sisApprove);
        sisInventoryCount.setMyApplyCount(new BigDecimal(sisApproves.size()));

        //我的待审批
        sisApprove = new SisApprove();
        sisApprove.setPhaseUserName(SecurityUtils.getLoginUser().getUser().getNickName());
        sisApproves = this.queryByPage(sisApprove);
        sisInventoryCount.setMyApproveCount(new BigDecimal(sisApproves.size()));

        //切除总数
        sisApprove = new SisApprove();
        sisApprove.setApproveType("1");
        sisApproves = this.sisApproveMapper.queryAllByLimit(sisApprove);
        sisInventoryCount.setResectionCount(new BigDecimal(sisApproves.size()));

        //恢复总数
        sisApprove.setApproveType("2");
        sisApproves = this.sisApproveMapper.queryAllByLimit(sisApprove);
        sisInventoryCount.setRecoveryCount(new BigDecimal(sisApproves.size()));

        return sisInventoryCount;
    }

    @Async
    public void sengwx(Integer userId, SisApprove sisApprove, String title) {
        EnterpriseWXServiceImpl.SendMessageRequest sendMessageRequest = new EnterpriseWXServiceImpl.SendMessageRequest();
        sendMessageRequest.setMsgtype("text");
        sendMessageRequest.setAgentid(1000319);
        EnterpriseWXServiceImpl.MessageContent messageContent = new EnterpriseWXServiceImpl.MessageContent();
        List<Integer> userIds = sysUserMapper.selectUserByPostName("SIS审批推送");
        Integer id = sysUserMapper.selectUserWXIdById(userId);
        userIds.add(id);
        sendMessageRequest.setTouser(CollUtil.join(userIds, "|"));
        messageContent.setContent("SIS系统" + sisApprove.getDeviceName() + "联锁" + (sisApprove.getApproveType().equals("1") ? "切除" : "恢复") + "正在" + title + "审批，请及时处理！");
        sendMessageRequest.setText(messageContent);
        enterpriseWXService.pushMessage(sendMessageRequest);
    }

    /**
     * 修改数据
     *
     * @param sisApprove 实例对象
     * @return 实例对象
     */
    @Override
    public SisApprove update(SisApprove sisApprove) {
        this.sisApproveMapper.update(sisApprove);
        return this.queryById(sisApprove.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.sisApproveMapper.deleteById(id) > 0;
    }


}
